import React from 'react';
import * as Icon from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import MenuConfig from '../../config/index';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { sekectMenuList } from '../../store/reducers/tab';
const { Sider } = Layout;

// 动态获取icon，创建菜单数据
const iconToElement = (name) => React.createElement(Icon[name])

// 处理菜单数据
const items = MenuConfig.map((item) => {
    // 没有子菜单的情况
    const child = {
        key: item.path,
        icon:iconToElement(item.icon),
        label: item.label
    }
    // 有子菜单的情况
    if(item.children) {
        child.children = item.children.map((item)=> {
            return {
                key:item.path,
                label:item.label
            }
        })
    }
    return child
})

// 菜单渲染  注意：父组件传过来的collapsed必须要用{}括起来，不括起来的话是对象
const CommonAside = ({collapsed}) => {
  const navigate = useNavigate()
  const dispatch = useDispatch()

  // 添加数据到store
  const setTabsList = (val) => {
    dispatch(sekectMenuList(val))
    
  }
  console.log(collapsed,'CommonAsied')
    // 点击菜单
  const selectMenu = (e) => {
    let data
    MenuConfig.forEach((item) => {
      // 找到当前的数据
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item
        // 如果是有二级菜单
        if (e.keyPath.length > 1) {
          data = item.children.find((child) => {
            return child.path === e.key
          })
        }
      }
    })
     setTabsList({
      path: data.path,
      name: data.name,
      label: data.label
    })
 
   navigate(e.key)
  }
return (
      <Sider trigger={null} collapsed={collapsed}>
       <h3 className="app-name">{collapsed? '后台' : '优选后台管理系统'}</h3>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1']}
          items={items}
          style={{
            height:'100%'
          }}
          onClick={selectMenu}
        />
      </Sider>
)

}
export default CommonAside;